package com.wx.leetcode;


/**
 * @desc:
 *
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 *
 * @author: wx
 * @time: 2020/6/1 4:36 PM
 */
public class LongestCommonPrefixTopic {

    
    public static void main(String args[]) {
        System.out.println(longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
        System.out.println(longestCommonPrefix(new String[]{"dog","racecar","car"}));
        System.out.println(longestCommonPrefix(new String[]{"aa","a"}));
    }
    
    
    public static String longestCommonPrefix(String[] strs) {

        if (strs == null){
            return "";
        }

        int length = strs.length;

        if (length == 0){
            return "";
        }

        //获取第一个字符串
        String oneStr = strs[0];

        for (int i = 1; i < length; i++) {
            int j = 0;
            char[] chars = strs[i].toCharArray();
            int l = chars.length < oneStr.length() ? chars.length : oneStr.length();
            for (;j < l; j++) {
                if (oneStr.charAt(j) != chars[j]){
                    break;
                }
            }
            oneStr = oneStr.substring(0,j);
        }

        return oneStr;
    }


}
